package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Category;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;



import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;


    /**
     * 分页模糊查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R pageQuery(int page,int pageSize,String name){
        Page<Setmeal> pageInfor=new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
        lqw.like(name!=null,Setmeal::getName,name).orderByAsc(Setmeal::getUpdateTime);
        setmealService.page(pageInfor,lqw);
        List<Setmeal> records = pageInfor.getRecords();
        Long total = pageInfor.getTotal();
        Map<String,Object> map=new HashMap<>();
        map.put("total",total);
        List<SetmealDto> list = records.stream().map(setmeal -> {
            SetmealDto setmealDto = new SetmealDto();
            Long categoryId = setmeal.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            setmealDto.setCategoryName(categoryName);
            BeanUtils.copyProperties(setmeal,setmealDto);//对象拷贝
            return setmealDto;
        }).collect(Collectors.toList());
        map.put("records",list);
        return R.success(map);
    }


    /**
     * 新增成功
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = {"setmeal"},allEntries = true)
    public R saveSetmeal(@RequestBody SetmealDto setmealDto){
          setmealService.saveSetmeal(setmealDto);
          return R.success("新增成功");
    }

    /**
     *更改状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = {"setmeal"},allEntries = true)
    public R changeSetmealStatus(@PathVariable Integer status,Long[] ids){
        LambdaUpdateWrapper<Setmeal> luw = new LambdaUpdateWrapper<>();
        luw.set(Setmeal::getStatus,status).in(Setmeal::getId,ids);
        setmealService.update(luw);
        return R.success("状态更改成功");
    }


    /**
     * 数据回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Cacheable(value = {"setmeal"},key="#id")
    public R getSetmealById(@PathVariable Long id){
        Setmeal setmeal = setmealService.getById(id);
        Long categoryId = setmeal.getCategoryId();
        Category category = categoryService.getById(categoryId);
        String categoryName = category.getName();//套餐分类名
        Long setmealId = setmeal.getId();
        LambdaUpdateWrapper<SetmealDish> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,setmealId);
        List<SetmealDish>  setmealDishes= setmealDishService.list(lqw);
        SetmealDto setmealDto = new SetmealDto();
        setmealDto.setCategoryName(categoryName);
        setmealDto.setSetmealDishes(setmealDishes);
        BeanUtils.copyProperties(setmeal,setmealDto);
        return R.success(setmealDto);
    }

    @PutMapping
    @CacheEvict(value = {"setmeal"},allEntries = true)
    public R updateSetmeal(@RequestBody SetmealDto setmealDto){
         setmealService.updateSetmeal(setmealDto);
         return R.success("修改成功");
    }

    @DeleteMapping
    @CacheEvict(value = {"setmeal"},allEntries = true)
    public R delSetmeal(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getStatus,0);
        lqw.in(Setmeal::getId,ids);
        int count = setmealService.count(lqw);
        if(count>0){
             throw new CustomException("商品正在起售，禁止删除");
        }
        //删除setmeal表中的数据
        setmealService.removeByIds(ids);
        //删除setmealdish表中的数据
        LambdaQueryWrapper<SetmealDish> lqws=new LambdaQueryWrapper<>();
        lqws.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lqws);
        return R.success("删除成功");
    }

    /**
     * 前台系统setmeal列表
     * @param setmeal
     * @return
     */
   // {categoryId:this.categoryId,status:1}
    @GetMapping("/list")
    @Cacheable(value = {"setmeal"},key="#setmeal.categoryId+'_'+#setmeal.status",unless = "#result==null")
    public R setmealList(Setmeal setmeal ){
       LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
       lqw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
       lqw.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
       lqw.orderByAsc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(lqw);
        return R.success(list);
    }

    @GetMapping("/dish/{id}")//id为setmeal表的id
    public R setMealDishDetails(@PathVariable Long id){
         //根据setmealid查询setmealdish表
        LambdaQueryWrapper<SetmealDish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(id!=null,SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishes = setmealDishService.list(lqw);
        return R.success(setmealDishes);
    }
}
